package com.bsj.power.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @ClassName HttpUtil
 * @Description Http请求工具了(针对tencent)
 * @Author yinhao
 * @Date 2024/7/11
 * @Version 1.0
 **/
@Slf4j
public class HttpUtil {
    public static String post(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！" + ExceptionUtil.getStackStr(e));
        }

        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error(ExceptionUtil.getStackStr(ex));
                ;
            }
        }
        return result;
    }

    //解析HTTP POST 请求数据
    public static String analysisPost(HttpServletRequest request) throws Exception {
        int len = request.getContentLength();
        if (len < 0) {
            return null;
        }
        byte[] buffer = new byte[len];
        ServletInputStream in = null;
        in = request.getInputStream();
        in.read(buffer, 0, len);
        String dataStr = new String(buffer);
        log.info("POST请求数据： {}", dataStr);
        return dataStr;
    }

    /**
     * 获取Post请求中的参数
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static String bufferedReadPost(HttpServletRequest request) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                log.warn("POST请求获取流数据为空！");
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 带有基本认证的 HTTP GET 请求
     *
     * @param url
     * @param username
     * @param password
     * @return
     */
    public static String doGetAuth(String url, String username, String password) {
        String responseBody = null;
        try {
            // 创建 HTTP GET 请求
            HttpRequest request = HttpRequest.get(url);
            // 设置基本认证
            String auth = username + ":" + password;
            String encodedAuth = Base64.encode(auth);
            request.header("Authorization", "Basic " + encodedAuth);
            // 发送请求并获取响应
            HttpResponse response = request.execute();
            // 检查响应状态码
            if (response.isOk()) {
                // 获取响应体
                responseBody = response.body();
//                log.info("Response: " + responseBody);
            } else {
                log.error("Failed to get resource: " + response.getStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    /**
     * 带有基本认证的 HTTP POST 请求
     *
     * @param url
     * @param body
     * @param username
     * @param password
     * @return
     */
    public static String doPostAuth(String url, String body, String username, String password) {
        // 构建基本认证的 Header
        String authHeader = "Basic " + StrUtil.utf8Str(Base64.encode((username + ":" + password).getBytes()));
        // 发送 POST 请求
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", authHeader)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(body)
                .execute();
        // 打印响应状态码和响应体
        return response.body();
    }

}
